<?php

namespace app\admin\service;

use app\model\Search;
use app\model\Videos;
// use think\facade\Session;
use app\model\Admin;

class SearchService
{
    private $model;
    private $videosModel;
    private $adminModel;

    public function __construct(Search $model, Videos $videosModel, Admin $adminModel)
    {
        $this->model = $model;
        $this->videosModel = $videosModel;
        $this->adminModel = $adminModel;
    }

    // 热门搜索列表
    public function getHotSearchList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->model->getPagingDataByWhere([], $page, $limit, 'id, video_id, admin_operator_user_id');

        if (!empty($data['data'])) {
            $videoIds = array_column($data['data'], 'video_id');
            $adminUserIds = array_column($data['data'], 'admin_operator_user_id');

            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videoResult = array_column($videoData, 'name', 'id');

            $userData = $this->adminModel->getDataByWhere(['id' => $adminUserIds], 'id, name');
            $userResult = array_column($userData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['video_name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']];
                $data['data'][$key]['admin_operator_user_name'] = empty($userResult[$item['admin_operator_user_id']]) ? '' : $userResult[$item['admin_operator_user_id']];
            }
        }

        return $data;
    }

    // 添加/编辑热门搜索
    public function editHotSearchData($params, $userInfo)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $params['admin_operator_user_id'] = $userInfo['user_id'];
        $id = $this->model->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 获取热门搜索设置详情
    public function getHotSearchDetail($id)
    {
        $data = $this->model->getInfoById($id, 'id, video_id, admin_operator_user_id, sort');
        return $data;
    }

    // 删除热门搜索设置
    public function deleteHotSearchData(int $id)
    {
        $bool = $this->model->destroy($id);

        if (!$bool) {
            return false;
        }

        return true;
    }
}